﻿// Copyright 2008 (c) Michael Reichenauer, SWEDEN. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;


namespace PSMock
{
	//PostSharp.exe "C:\Program files\PostSharp 1.0\Default.psproj" MyAssembly.dll /p:Output=MyAssembly_PS.dll /p:IntermediateDirectory=. /p:CleanIntermediate=false 


	public class PostSharpProcess
	{

		public static void PrepareMocking(string assemblyName)
		{
			try
			{
				Console.WriteLine("Staring PostSharp processing");
				Stopwatch stopwatch = new Stopwatch();
				stopwatch.Start();
				string localDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				string assemblyPath = localDir + "\\" + assemblyName;
				string assemblyCopyPath = localDir + "\\" + assemblyName + ".copy.dll";
				string assemblyTempPath = localDir + "\\" + assemblyName + ".temp.dll";

				if (!File.Exists(assemblyCopyPath)
					|| File.GetLastWriteTime(assemblyPath) != File.GetLastWriteTime(assemblyCopyPath))
				{
					Console.WriteLine("{0}, {1}", File.GetLastWriteTime(assemblyPath), File.GetLastWriteTime(assemblyCopyPath));

					File.Copy(assemblyPath, assemblyTempPath, true);
					File.Delete(assemblyCopyPath);


					// Start the child process.
					Process p = new Process();
					// Redirect the output stream of the child process.
					p.StartInfo.UseShellExecute = false;
					//p.StartInfo.RedirectStandardOutput = true;
					p.StartInfo.RedirectStandardError = true;
					p.StartInfo.FileName = localDir + "\\PostSharp.exe";
					p.StartInfo.Arguments = "\"" + localDir + "\\Default.psproj\" " +
						"\"" + assemblyTempPath + "\" " +
						"/p:Output=\"" + assemblyPath + "\" " +
						"/p:SearchPath=, /p:IntermediateDirectory=PostSharp /p:CleanIntermediate=true /p:SignAssembly=False /p:PrivateKeyLocation=";


					p.Start();
					//string output = p.StandardOutput.ReadToEnd();
					string output = p.StandardError.ReadToEnd();
					p.WaitForExit();
					if (!string.IsNullOrEmpty(output))
					{
						throw new InvalidOperationException("PostSharp error: " + output);
					}

					File.Copy(assemblyPath, assemblyCopyPath, true);
					File.Delete(assemblyTempPath);
				}
				stopwatch.Stop();
				Console.WriteLine("PostSharp time: {0}ms", stopwatch.ElapsedMilliseconds);
			}
			catch (Exception e)
			{
				Console.WriteLine("PostSharp Exception:\n" + e);
			}
		}

	}
}
